﻿using System;
using System.Windows;
using System.Windows.Interactivity;
using System.Windows.Media;

namespace GameLogic.Logic
{
    public class StaticCollidableBehavior: GameLoopBehavior<FrameworkElement>, ICollidable
	{
        #region ICollidable Members
        public Rect Rect
        {
            get
            {
                try
                {
                    UIElement root = this.GameLoop.RootElement as UIElement;
                    Point upperLeft = this.AssociatedObject.TransformToVisual(root).Transform(new Point(0, 0));
                    return new Rect(upperLeft, new Size(this.AssociatedObject.ActualWidth, this.AssociatedObject.ActualHeight));
                }
                catch
                {
                    Point position = new Point(0, 0);
                    return new Rect(position, new Size(this.AssociatedObject.ActualWidth, this.AssociatedObject.ActualHeight));
                }
            }
        }
        #endregion
       
        protected override void OnGameLoopInitialized()
		{
            // Add element to static collision list
            this.GameLoop.RegisterAsStaticCollidable(this.AssociatedObject);
            this.GameLoop.Reset += this.OnReset;
		}

        private void OnReset(object sender, EventArgs e)
        {
            this.UnregisterCollidableIfNecessary();
        }

        private void UnregisterCollidableIfNecessary()
        {
            // check to see if we're still in the tree and remove ourselves if not
            FrameworkElement element = this.AssociatedObject;
            while (element != null)
            {
                if (element.Equals(this.GameLoop.RootElement as FrameworkElement))
                {
                    return;
                }
                element = VisualTreeHelper.GetParent(element) as FrameworkElement;
            }

            // Remove element from static collision list
            this.GameLoop.UnregisterAsStaticCollidable(this.AssociatedObject);
        }
	}
}
